﻿using ConfExpert.Forms.Base;
using ConfExpert.Utility;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraVerticalGrid.Rows;
using DevTeam;
using System;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace ConfExpert.Forms.Siparisler
{
    public partial class YuklemeFormu2 : XForm
    {
        int YuklemePartisiId;
        public YuklemeFormu2(int YuklemePartisiId)
        {
            InitializeComponent();
            this.YuklemePartisiId = YuklemePartisiId;
        }

        private void YuklemeFormu2_Load(object sender, EventArgs e)
        {
            this.vgc.LayoutStyle = DevExpress.XtraVerticalGrid.LayoutViewStyle.SingleRecordView;

            btnSave.ItemClick += btnSave_ItemClick;
            btnSaveAsDefault.ItemClick += btnSaveAsDefault_ItemClick;
            btnExcel.ItemClick += btnExcel_ItemClick;
            //this.btnSaveAsDefault.Enabled = false;

            Getir();
        }


        void btnSaveAsDefault_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (XtraMessageBox.Show("Girilen değerler varsayılan olarak kaydedilecek.", "Teyid", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                string str = (this.vgc.DataSource as DataTable).Serialize();
                ExecuteNonQuery("UpdCustomerPref", str);
                Notify("Kaydedildi.");
            }
        }

        void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

            DataTable t = this.vgc.DataSource as DataTable;
            if (ihr)
                t.Columns["UreticiFirma"].DefaultValue = null;
            else
            {
                t.Columns["IhracatciFirma"].DefaultValue = null;
                t.Columns["MusterininBankaIsmi"].DefaultValue = null;
                t.Columns["BankaTelNo"].DefaultValue = null;
                t.Columns["BankaFaxNo"].DefaultValue = null;
                t.Columns["HesapNumarasi"].DefaultValue = null;
                t.Columns["IbanNo"].DefaultValue = null;
                t.Columns["SwiftCodeNo"].DefaultValue = null;
                t.Columns["LC_AkreditifNo"].DefaultValue = null;
            }

            this.vgc.CloseEditor();
            string xml = t.Serialize();
            ExecuteNonQuery("InsYuklemeFormu", xml, YuklemePartisiId, ihr ? "İHRACAT" : "İÇ PİYASA", WhoAmI);
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            Notify("Kaydedildi");
        }

        bool ihr;
        private void Getir()
        {
            DataTable t = ExecuteDataTable("GetCustomerPrefByYuklemePartisiId", YuklemePartisiId);
            if (t.Rows[0]["CustomerId"].ToInt() > 0)
            {
                ihr = AppSession.Lookups.V_Customer.FindByCustomerId(t.Rows[0]["CustomerId"].ToInt()).CountryId != 10;
                this.Text = (ihr ? "İHRACAT Yükleme Formu - " : "İÇ PİYASA Yükleme Formu - ") + AppSession.Lookups.V_Customer.FindByCustomerId(t.Rows[0]["CustomerId"].ToInt()).Name;
            }

            vgc.Rows.Clear();

            AddVerticalGridGroup(vgc, "YÜKLEMEYE ÖZEL", new BaseRow[] { 
                    AddItem("Müşteri Temsilcisi", "UserId", typeof(int), RI(Rp.V_User)),
                    ihr? AddItem("İhracatçı Firma","IhracatciFirma", typeof(string)): AddItem("Üretici Firma","UreticiFirma", typeof(string)),
                    AddItem("Ürün Yükleme Tarihi","UrunYuklemeTarihi", typeof(DateTime))
                     });

            AddVerticalGridGroup(vgc, "FATURA BİLGİLERİ", new BaseRow[] { 
                    AddItem("Adres1","FaturaAdresi", typeof(string)),
                    AddItem("Adres2","FaturaAdresi2", typeof(string)),
                    AddItem("Posta Kodu","FPostalCode", typeof(string)),
                    AddItem("Şehir","FCity", typeof(string)),
                    AddItem("Ülke","FCountryId", typeof(int), RI(Rp.Country)),
                    AddItem("Kontak Kişi","FKontakKisi", typeof(string)),
                    AddItem("Tel","FTel", typeof(string)),
                    AddItem("Fax","FFax", typeof(string)),
                    AddItem("Email","FEMail", typeof(string))
                     });

            AddVerticalGridGroup(vgc, "TESLİMAT BİLGİLERİ", new BaseRow[] { 
                    AddItem("Adres1", "TeslimatAdresi", typeof(string)),
                    AddItem("Adres2", "TeslimatAdresi2", typeof(string)),
                    AddItem("Posta Kodu", "TPostalCode", typeof(string)),
                    AddItem("Şehir", "TCity", typeof(string)),
                    AddItem("Ülke", "TCountryId", typeof(int), RI(Rp.Country)),
                    AddItem("Kontak Kişi", "TKontakKisi", typeof(string)),
                    AddItem("Tel", "TTel", typeof(string)),
                    AddItem("Fax", "TFax", typeof(string)),
                    AddItem("Email", "TEMail", typeof(string))
                     });

            if (ihr)
            {
                AddVerticalGridGroup(vgc, "BANKA", new BaseRow[] { 
                    AddItem("İsmi", "MusterininBankaIsmi", typeof(string)),
                    AddItem("Tel No", "BankaTelNo", typeof(string)),
                    AddItem("Fax No","BankaFaxNo", typeof(string)),
                    AddItem("Hesap No","HesapNumarasi", typeof(string)),
                    AddItem("IBAN No","IbanNo", typeof(string)),
                    AddItem("SWIFT Code No","SwiftCodeNo", typeof(string)),
                    AddItem("Vergi No","VergiNo", typeof(string))
                     });

                AddVerticalGridGroup(vgc, "ÖDEME ve YÜKLEME ŞEKLİ", new BaseRow[] { 
                    AddItem("Ödeme Vadesi", "PaymentTermId", typeof(int), RI(Rp.PaymentTerm)),
                    AddItem("Ödeme Şekli","PaymentMethodId", typeof(int), RI(Rp.PaymentMethodS)),
                    AddItem("LC (akreditif) No", "LC_AkreditifNo", typeof(string)),
                    AddItem("Ödeme Notu","OdemeNotu", typeof(string)),
                    AddItem("Yükleme Şekli","ShipMethodId", typeof(int), RI(Rp.ShipMethod)),
                    AddItem("Teslim Şekli","TeslimSekliSId", typeof(int), RI(Rp.TeslimSekliS))
                     });
            }
            else
                AddVerticalGridGroup(vgc, "ÖDEME ve YÜKLEME ŞEKLİ", new BaseRow[] { 
                    AddItem("Ödeme Vadesi", "PaymentTermId", typeof(int), RI(Rp.PaymentTerm)),
                    AddItem("Ödeme Şekli","PaymentMethodId", typeof(int), RI(Rp.PaymentMethodS)),
                    AddItem("Ödeme Notu","OdemeNotu", typeof(string)),
                    AddItem("Yükleme Şekli","ShipMethodId", typeof(int), RI(Rp.ShipMethod)),
                    AddItem("Teslim Şekli","TeslimSekliSId", typeof(int), RI(Rp.TeslimSekliS))
                     });

            AddVerticalGridGroup(vgc, "NAKLİYECİ", new BaseRow[] { 
                    //Yükleme Şekli FOB yada EXW ise:(müşterinin nakliyecisi kullanılıyorsa…)
                    AddItem("Adı",  "NakliyeciAdı", typeof(string)), //RI(Rp.Nakliyeci)),
                    AddItem("Adresi", "NakliyeciAddress", typeof(string)),
                    AddItem("Tel No", "NakliyeciTelNo", typeof(string)),
                    AddItem("Fax No", "NakliyeciFaxNo", typeof(string)),
                    AddItem("Email", "NakliyeciEmail", typeof(string)),
                    AddItem("Kontak Kişi", "NakliyeciKontakKisi", typeof(string))
                    });

            AddVerticalGridGroup(vgc, "DİĞER", new BaseRow[] { 
                    AddItem("Koli Ölçüsü", "KoliOlcusu", typeof(string)),
                    AddItem("İç Koli Kaçlık","IcKoliKapasite", typeof(string)),
                    AddItem("Dış Koli Kaçlık","DisKoliKapasite", typeof(string)),
                    AddItem("Aynı Koliye Birden Çok Renk?","AyniKoliyeBirdenCokRenk", typeof(bool)),                    
                    AddItem("Askılı Gömlek Adedi","AskiliGomlekAdet", typeof(string)),
                    AddItem("NumuneOnayiBekleniyorMu","NumuneOnayiBekleniyorMu", typeof(bool)),
                    AddItem("MusteriInspectionVarMi","MusteriInspectionVarMi", typeof(bool)),
                    AddItem("Özel Notlar","OzelNotlar", typeof(string))
                    });

            vgc.Rows.GetRowByFieldName("OzelNotlar", true).Height = 80;
            vgc.CustomDrawRowHeaderCell -= new DevExpress.XtraVerticalGrid.Events.CustomDrawRowHeaderCellEventHandler(vgc_CustomDrawRowHeaderCell);
            vgc.CustomDrawRowHeaderCell += new DevExpress.XtraVerticalGrid.Events.CustomDrawRowHeaderCellEventHandler(vgc_CustomDrawRowHeaderCell);
            vgc.Appearance.RowHeaderPanel.BackColor = Color.LightBlue;
            vgc.DataSource = t;

            vgc.SetCellValue(vgc.Rows["UserId"], 0, WhoAmI);
            vgc.Rows.GetRowByFieldName("UserId", true).Properties.ReadOnly = true;
            vgc.BestFit();
        }


        public BaseRow AddItem(string caption, string name, Type t, params RepositoryItem[] ri)
        {
            int RowHeight = 20;
            BaseRow row = vgc.Rows.GetRowByFieldName(name);
            if (row == null)
            {
                row = new EditorRow();
                row.Name = row.Properties.FieldName = name;
            }
            row.Properties.Caption = caption;
            row.Height = RowHeight;
            //row.Properties.Value = null;
            if (ri.Length > 0)
                row.Properties.RowEdit = ri[0];

            return row;
        }



        void btnExcel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //DataRow dr = this.gridView1.GetFocusedDataRow();
            DataRow dr = (this.vgc.DataSource as DataTable).Rows[0];


            DataTable t = ExecuteDataTable("GetForms", dr["FormType"]);
            FileToSend = ByteArrayToFile3(t.Rows[0]["Name"].ToString() + t.Rows[0]["FileExtension"], t.Rows[0]["File"] as byte[]);

            SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(FileToSend);
            SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets[0];
            SpreadsheetGear.IRange cells = workbook.Worksheets[0].Cells;

            SpreadsheetGear.INames names = workbook.Names;
            foreach (SpreadsheetGear.IName n in names)
            {
                switch (n.Name)
                {
                    case "InsertedOn": cells[n.Name].Value = dr["InsertedOn"]; break;
                }
            }

            //names.Add("Jan", "='2005 Sales'!$B$2:$B$4");
            //names.Add("Feb", "='2005 Sales'!$C$2:$C$4");
            //names.Add("Mar", "='2005 Sales'!$D$2:$D$4");
            //names.Add("Sales", "='2005 Sales'!$B$2:$D$4");
            //// Format sales data as currency.
            //cells["Sales"].NumberFormat = "$#,##0";



            cells[2, 1].Value = dr["InsertedOn"];

            cells[5, 1].Value = AppSession.Lookups.V_Customer.FindByCustomerId(intParse(dr["CustomerId"])).Name;
            cells[6, 1].Value = dr["UserId"].ToString() == "" ? "" : AppSession.Lookups.V_User.FindByUserId(intParse(dr["UserId"])).Username;
            cells[8, 1].Value = dr["UrunYuklemeTarihi"];

            cells[11, 1].Value = dr["FaturaAdresi"];
            cells[12, 1].Value = dr["FaturaAdresi2"];
            cells[13, 1].Value = dr["FPostalCode"];
            cells[14, 1].Value = dr["FCity"];
            cells[15, 1].Value = dr["FCountryId"].ToString() == "" ? "" : AppSession.Lookups.Country.FindByCountryId(intParse(dr["FCountryId"])).Name;

            cells[17, 1].Value = dr["FKontakKisi"];
            cells[18, 1].Value = dr["FTel"];
            cells[19, 1].Value = dr["FFax"];
            cells[20, 1].Value = dr["FEMail"];

            cells[23, 1].Value = dr["TeslimatAdresi"];
            cells[24, 1].Value = dr["TeslimatAdresi2"];
            cells[25, 1].Value = dr["TPostalCode"];
            cells[26, 1].Value = dr["TCity"];
            cells[27, 1].Value = dr["TCountryId"].ToString() == "" ? "" : AppSession.Lookups.Country.FindByCountryId(intParse(dr["TCountryId"])).Name;

            cells[29, 1].Value = dr["TKontakKisi"];
            cells[30, 1].Value = dr["TTel"];
            cells[31, 1].Value = dr["TFax"];
            cells[32, 1].Value = dr["TEMail"];


            string numune = "";
            string musInsp = "";

            if (dr["NumuneOnayiBekleniyorMu"].ToString() == "True")
                numune = "Evet";
            else if (dr["NumuneOnayiBekleniyorMu"].ToString() == "False")
                numune = "Hayır";

            if (dr["MusteriInspectionVarMi"].ToString() == "True")
                musInsp = "Evet";
            else if (dr["MusteriInspectionVarMi"].ToString() == "False")
                musInsp = "Hayır";


            if (t.Rows[0]["Name"].ToString() == "İHRACAT YÜKLEME FORMU")
            {
                cells[7, 1].Value = dr["IhracatciFirma"];

                cells[35, 1].Value = dr["MusterininBankaIsmi"];
                cells[36, 1].Value = dr["BankaTelNo"];
                cells[37, 1].Value = dr["BankaFaxNo"];
                cells[38, 1].Value = dr["HesapNumarasi"];
                cells[39, 1].Value = dr["IbanNo"];
                cells[40, 1].Value = dr["SwiftCodeNo"];
                cells[41, 1].Value = dr["VergiNo"];

                cells[43, 1].Value = dr["PaymentTermId"];
                cells[44, 1].Value = dr["PaymentMethodId"];
                cells[46, 1].Value = dr["LC_AkreditifNo"];
                cells[48, 1].Value = dr["OdemeNotu"];

                cells[51, 1].Value = dr["ShipMethodId"].ToString() == "" ? "" : AppSession.Lookups.ShipMethod.FindByShipMethodId(intParse(dr["ShipMethodId"])).Name;
                cells[52, 1].Value = dr["TeslimSekliSId"].ToString() == "" ? "" : AppSession.Lookups.TeslimSekliS.FindByTeslimSekliSId(intParse(dr["TeslimSekliSId"])).Name;

                cells[57, 1].Value = dr["NakliyeciAdi"];
                cells[58, 1].Value = dr["NakliyeciAddress"];
                cells[59, 1].Value = dr["NakliyeciTelNo"];
                cells[60, 1].Value = dr["NakliyeciFaxNo"];
                cells[61, 1].Value = dr["NakliyeciEmail"];
                cells[62, 1].Value = dr["NakliyeciKontakKisi"];

                cells[66, 1].Value = dr["KoliOlcusu"];
                cells[67, 1].Value = dr["IcKoliKapasite"];
                cells[68, 1].Value = dr["AskiliGomlekAdet"];

                cells[72, 1].Value = numune;
                cells[73, 1].Value = musInsp;

                cells[76, 1].Value = dr["OzelNotlar"];
            }
            else
            {
                cells[7, 1].Value = dr["UreticiFirma"];

                cells[36, 1].Value = dr["PaymentTermId"];
                cells[37, 1].Value = dr["PaymentMethodId"];
                cells[39, 1].Value = dr["OdemeNotu"];

                cells[40, 1].Value = dr["VergiNo"];

                cells[47, 1].Value = dr["ShipMethodId"].ToString() == "" ? "" : AppSession.Lookups.ShipMethod.FindByShipMethodId(intParse(dr["ShipMethodId"])).Name;
                cells[48, 1].Value = dr["TeslimSekliSId"].ToString() == "" ? "" : AppSession.Lookups.TeslimSekliS.FindByTeslimSekliSId(intParse(dr["TeslimSekliSId"])).Name;

                cells[53, 1].Value = dr["NakliyeciAdi"];
                cells[54, 1].Value = dr["NakliyeciAddress"];
                cells[55, 1].Value = dr["NakliyeciTelNo"];
                cells[56, 1].Value = dr["NakliyeciFaxNo"];
                cells[57, 1].Value = dr["NakliyeciEmail"];
                cells[58, 1].Value = dr["NakliyeciKontakKisi"];

                cells[62, 1].Value = dr["KoliOlcusu"];
                cells[63, 1].Value = dr["IcKoliKapasite"];
                cells[64, 1].Value = dr["AskiliGomlekAdet"];

                cells[69, 1].Value = numune;
                cells[70, 1].Value = musInsp;

                cells[73, 1].Value = dr["OzelNotlar"];
            }

            string FileName = FileToSend;
            workbook.SaveAs(FileName, SpreadsheetGear.FileFormat.OpenXMLWorkbook);
            FileManager.RunFile(FileName);


        }

        string FileToSend;
        public string ByteArrayToFile3(string filePath, byte[] content)
        {
            string FullPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache) + "\\" + filePath;
            using (FileStream fs = new FileStream(FullPath, FileMode.Create, FileAccess.Write))
            {
                using (BinaryWriter bw = new BinaryWriter(fs))
                {
                    bw.Write(content);
                    bw.Flush();
                }
            }

            return FullPath;
        }
    }
}
